// pages/songDetail/songDetail.js
import request from '../../utils/request';

Page({

  /**
   * 页面的初始数据
   */
  data: {
      isPlay: false,
      song: {},
      musicId:""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
      // console.log(JSON.stringify(options))
      let musicId = options.musicId;
      this.setData({
        musicId
      })
      this.getMusiscInfo(musicId);
      this.backgroundAudioManager =  wx.getBackgroundAudioManager();
      this.backgroundAudioManager.onPlay(() => {
        this.changePlayState(true);
      });
      this.backgroundAudioManager.onPause(() => {
        this.changePlayState(false)
      }),
      this.backgroundAudioManager.onStop(() => {
        this.changePlayState(false)
      })
  },

  changePlayState(isPlay){
    this.setData({
      isPlay: isPlay
    })
  },

  async getMusiscInfo(musicId){
    let songData = await request('/song/detail',{ids: musicId})
    console.log(songData)
    this.setData({
        song: songData.songs[0]
    })
    wx.setNavigationBarTitle({
      title: this.data.song.name,
    })

  },

  handleMusicPlay() {
    let isPlay = !this.data.isPlay;
    // this.setData({
    //   isPlay:!this.data.isPlay
    // }) 
    let {musicId} = this.data;
    this.musicControl(isPlay,musicId);
  },

  async musicControl(isPlay,musicId){
    if(isPlay){
      let musicLinkData = await request('/song/url',{id: musicId});
      let musicLink = musicLinkData.data[0].url;
      this.backgroundAudioManager.src = musicLink;
      console.log("musicLink",musicLink)
      this.backgroundAudioManager.title = this.data.song.name;
    }else{
      this.backgroundAudioManager.pause();
    }
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})